package com.wh.codedemon.datastructure;

import java.sql.Array;

/**
 * 八皇后问题
 */
public class Queen8 {

    static int max = 8, count = 0;
    int[] array = new int[8];


    public static void main(String[] args) {
        Queen8 queen8 = new Queen8();
        queen8.check(0);
        System.out.printf("一共有%d种解法", count);
    }

    private void check(int n) {
        if (n == max) {
            printOut();
            count++;
            return;
        }
        for (int i = 0; i < max; i++) {
            array[n] = i;

            if (isSafe(n)) {
                // 不冲突,则继续下一个
                check(n + 1);
            }
        }
    }

    private boolean isSafe(int n) {
        // 列相等 或 斜线
        for (int i = 0; i < n; i++) {
            if (array[n] == array[i] || Math.abs(n - i) == Math.abs(array[n] - array[i])) {
                return false;
            }
        }
        return true;
    }

    private void printOut() {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
        System.out.println();
    }
}
